package fragments.shopactivity;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.travel.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fragments.shopadapter.RootListViewAdapter;
import fragments.shopadapter.ShopGriOneItemAdapter;
import fragments.shopadapter.SubListViewAdapter;
import shopbean.GvOneBena;
import shopbean.contans.ShopURL;
import tools.Okhttputils;
import tools.ScreenUtils;

/**
 * Created by Administrator on 2016/10/20.
 */
public class GridViewOneActivity extends AppCompatActivity implements View.OnClickListener{
    private PopupWindow popupWindow,popupWindowTo,popupWindowDay,popupWindowTime;
    private ListView listView,gvListView,listViewDays;
    private TextView tv,tvTo,tvTime,tvDay;
    private ShopGriOneItemAdapter adapter;
    //39,1,5,9,7,10,2,11
    private String int1[]=new String[]{"39","1","5","9","7","10","2","11"};
    //daysSelect=0,68,17,18,19,21
    private String days[]=new String[]{"0","68","17","18","19","21"};
    private List<GvOneBena.DataBean.LineBean> list=new ArrayList<>();
    private String path;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    list= (List<GvOneBena.DataBean.LineBean>) msg.obj;
                    adapter=new ShopGriOneItemAdapter(GridViewOneActivity.this,list);
                    gvListView.setAdapter(adapter);
                    break;
            }
        }
    };
    /**
     * 二级菜单的根目录
     */
    private ListView rootListView;
    //根目录
    private String[] roots = new String[] { "不限目的地", "热门地区", "免签","海岛","港澳台","东南亚",
            "日韩","欧洲","西亚","北美洲","大洋洲","非洲","南美洲" };
    /**
     * 子目录节点
     */
    private String[][] sub_items = new String[][] {
            new String[] { "不限目的地" },
            new String[] { "港澳台","东南亚","欧洲","马尔代夫","美国","澳大利亚"},
            new String[] { "免签" ,"泰国","印度尼西亚","马尔代夫","巴厘岛","济州岛"},
            new String[] { "海岛" ,"泰国","印度尼西亚","巴厘岛","民代岛","马尔代夫"},
            new String[] { "港澳台" ,"台湾","澳门","香港"}};
    private ListView subListView;
    private LinearLayout popupLayout;
    /**
     * 子目录的布局
     */
    private FrameLayout subLayout;

    /**
     * 根目录被选中的节点
     */
    private int selectedPosition;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shop_gv_onitem);

        path = ShopURL.GVITEMH+int1[0]+ShopURL.GVITEMF;
        gvListView= (ListView) findViewById(R.id.shop_gvOne_on);
        tv= (TextView) findViewById(R.id.main_tab1);
        tvTo= (TextView) findViewById(R.id.shop_to);
        tvTime= (TextView) findViewById(R.id.shop_time);
        tvDay= (TextView) findViewById(R.id.shop_days);
        tv.setOnClickListener(this);
        tvTo.setOnClickListener(this);
        tvDay.setOnClickListener(this);
        tvTime.setOnClickListener(this);
        initControls();
        inData();
    }

    private void inData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String jsonString= Okhttputils.getInstance().run(path);
                    JSONObject obj=JSONObject.parseObject(jsonString).getJSONObject("data");
                    String line=obj.getString("line");
                    List<GvOneBena.DataBean.LineBean> list=new ArrayList<GvOneBena.DataBean.LineBean>();
                    list= JSONArray.parseArray(line,GvOneBena.DataBean.LineBean.class);
                    Message message=new Message();
                    message.what=1;
                    message.obj=list;
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void initControls() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.shop_gvone_pupo, null);
        SimpleAdapter adapter = new SimpleAdapter(this, getData(),
                R.layout.shop_popu_item,
                new String[] { "text" },
                new int[] { R.id.item });
        listView = (ListView) view.findViewById(R.id.pop_listview);
        listView.setAdapter(adapter);

        //自适配长、框设置
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,true);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                path = ShopURL.GVITEMH+int1[i]+ShopURL.GVITEMF;
                inData();
             if(popupWindow.isShowing()){
                    popupWindow.dismiss();
                }
            }
        });
        //第三个
        View viewDay=inflater.inflate(R.layout.shop_gvone_pupo, null);
        SimpleAdapter adapterDay = new SimpleAdapter(this, getDataDay(),
                R.layout.shop_popu_item,
                new String[] { "text" },
                new int[] { R.id.item });
        listView = (ListView) viewDay.findViewById(R.id.pop_listview);
        listView.setAdapter(adapterDay);
        //自适配长、框设置
        popupWindowDay = new PopupWindow(viewDay, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,true);
        popupWindowDay.setTouchable(true);
        popupWindowDay.setOutsideTouchable(true);
        popupWindowDay.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        popupWindowDay.getContentView().setFocusableInTouchMode(true);
        popupWindowDay.getContentView().setFocusable(true);
        //第四个 popupWindow
        View viewTime=inflater.inflate(R.layout.shop_gvone_pupo, null);
        SimpleAdapter adapterTime = new SimpleAdapter(this, getDataTime(),
                R.layout.shop_popu_item,
                new String[] { "text" },
                new int[] { R.id.item });
        listView = (ListView) viewTime.findViewById(R.id.pop_listview);
        listView.setAdapter(adapterTime);
        //自适配长、框设置
        popupWindowTime = new PopupWindow(viewTime, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,true);
        popupWindowTime.setTouchable(true);
        popupWindowTime.setOutsideTouchable(true);
        popupWindowTime.getContentView().setFocusableInTouchMode(true);
        popupWindowTime.getContentView().setFocusable(true);
        popupWindowTime.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        popupWindowTime.setAnimationStyle(android.R.style.Animation_Dialog);
    }

    private List< Map<String,String>> getDataDay() {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        Map<String, String> map = new HashMap<String, String>();
        map.put("text", "不限天数");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "1-2");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "3-5");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "6-8");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "9-11");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "12天以上");
        list.add(map);
        return list;
    }
    private List<Map<String,String>> getDataTime() {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        Map<String, String> map = new HashMap<String, String>();
        map.put("text", "不限时间");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "2016—10");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "2016-11");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "2016-12");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "2017-01");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "2017-02");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "2017-03");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "2017-04");
        list.add(map);
        return list;
    }

    private List<Map<String, String>> getData() {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        Map<String, String> map = new HashMap<String, String>();
        map.put("text", "自由行");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "当地玩乐");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "签证");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "接送机");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "WIFI租赁");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "电话卡");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "景点门票");
        list.add(map);
        map = new HashMap<String, String>();
        map.put("text", "演出门票");
        list.add(map);
        return list;
    }
    //点击事件
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.main_tab1:
                if (!popupWindow.isShowing()) {
                    popupWindow.showAsDropDown(tv, 0, 0);
                    popupWindow.showAtLocation(tv, Gravity.CENTER, 0, 0);
                }
            break;
            case R.id.shop_days:
                if (!popupWindowDay.isShowing()) {
                    popupWindowDay.showAsDropDown(tv, 0, 0);
                    popupWindowDay.showAtLocation(tv, Gravity.CENTER, 0, 0);
                }
                break;
            case R.id.shop_time:
                if (!popupWindowTime.isShowing()) {
                    popupWindowTime.showAsDropDown(tv, 0, 0);
                    popupWindowTime.showAtLocation(tv, Gravity.CENTER, 0, 0);
                }
                break;
            case R.id.shop_to:
                tvTo(ScreenUtils.getScreenWidth(GridViewOneActivity.this),
                        ScreenUtils.getScreenHeight(GridViewOneActivity.this));
                break;
        }
    }

    private void tvTo(int screenWidth, int screenHeight) {
        LayoutInflater inflater = LayoutInflater.from(GridViewOneActivity.this);
        popupLayout = (LinearLayout) inflater.inflate(
                R.layout.popup_layout, null, false);
        rootListView = (ListView) popupLayout.findViewById(R.id.root_listview);
        final RootListViewAdapter adapter = new RootListViewAdapter(
                GridViewOneActivity.this);
        adapter.setItems(roots);
        rootListView.setAdapter(adapter);

        /**
         * 子popupWindow
         */
        subLayout = (FrameLayout) popupLayout.findViewById(R.id.sub_popupwindow);

        /**
         * 初始化subListview
         */
        subListView = (ListView) popupLayout.findViewById(R.id.sub_listview);

        /**
         * 弹出popupwindow时，二级菜单默认隐藏，当点击某项时，二级菜单再弹出
         */
        subLayout.setVisibility(View.INVISIBLE);

        /**
         * 初始化mPopupWindow
         */
        popupWindowTo = new PopupWindow(popupLayout, screenWidth,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
/**
 * 有了mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
 * 这句可以使点击popupwindow以外的区域时popupwindow自动消失 但这句必须放在showAsDropDown之前
 */
        popupWindowTo.setBackgroundDrawable(new BitmapDrawable());

        /**
         * popupwindow的位置，第一个参数表示位于哪个控件之下 第二个参数表示向左右方向的偏移量，正数表示向左偏移，负数表示向右偏移
         * 第三个参数表示向上下方向的偏移量，正数表示向下偏移，负数表示向上偏移
         *
         */
        popupWindowTo.showAsDropDown(tvTo, -5, 5);// 在控件下方显示popwindow

        popupWindowTo.update();

        rootListView
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        // TODO Auto-generated method stub

                        /**
                         * 选中root某项时改变该ListView item的背景色
                         */
                        adapter.setSelectedPosition(position);
                        adapter.notifyDataSetInvalidated();

                        selectedPosition = position;

                        SubListViewAdapter subAdapter = new SubListViewAdapter(
                                GridViewOneActivity.this, sub_items, position);
                        subListView.setAdapter(subAdapter);

                        /**
                         * 选中某个根节点时，使显示相应的子目录可见
                         */
                        subLayout.setVisibility(View.VISIBLE);
                        subListView
                                .setOnItemClickListener(new AdapterView.OnItemClickListener() {

                                    @Override
                                    public void onItemClick(
                                            AdapterView<?> parent, View view,
                                            int position, long id) {
                                        // TODO Auto-generated method stub
//                                       inData();
                                        popupLayout.setVisibility(View.GONE);
                                        Toast.makeText(GridViewOneActivity.this,"数据已更新",Toast.LENGTH_LONG).show();
                                    }
                                });

                    }
                });
    }

}